<template>
  <div>
    <div class="ocr-box" v-if="type == 'idCard'">
      <div class="just-box">
        <div class="upload-box">
          <div class="perch-box" v-if="!just">
            <!-- <img :src="require('@/assets/justCard.png')" style="width: 100%; height: 100%" alt=""/> -->
            <div class="positon-box">
              <div class="camera-box">
                <!-- <img :src="require('@/assets/camera-fill.svg')" style="width: 70%" alt=""/> -->
              </div>
            </div>
          </div>
          <div class="return-box" v-if="just">
            <img :src="just" style="width: 100%; height: 100%" alt=""/>
          </div>
          <form ref="justForm" v-show="schema != 'android' && schema != 'ios'">
            <input
              ref="justCard"
              type="file"
              class="file-input"
              accept="image/*"
              capture="camera"
              @change="uploadJustImg"
              :disabled="isDisabled"
            />
          </form>
          <div class="loading-mask" v-if="uploadLoading.just">
            <spinner type="lines"></spinner>
          </div>
        </div>
        <div class="upload-hint">拍摄身份证头像面</div>
        <!-- <div>{{justInfo}}</div> -->
      </div>
      <div class="back-box">
        <div class="upload-box" @click="uploadOcrApp('backCard')">
          <div class="perch-box" v-if="!back">
            <!-- <img :src="require('@/assets/backCard.png')" style="width: 100%; height: 100%" alt=""/> -->
            <div class="positon-box">
              <div class="camera-box">
                <!-- <img :src="require('@/assets/camera-fill.svg')" style="width: 70%" alt=""/> -->
              </div>
            </div>
          </div>
          <div class="return-box" v-if="back">
            <img :src="back" style="width: 100%; height: 100%" alt=""/>
          </div>
          <form ref="backForm" v-show="schema != 'android' && schema != 'ios'">
            <input
              ref="backCard"
              type="file"
              class="file-input"
              accept="image/*"
              @change="uploadBackImg"
              :disabled="isDisabled"
            />
          </form>
          <div class="loading-mask" v-if="uploadLoading.back">
            <spinner type="lines"></spinner>
          </div>
        </div>
        <div class="upload-hint">拍摄身份证国徽面</div>
        <!-- <div>{{backInfo}}</div> -->
      </div>
    </div>
    <div class="ocr-box" v-if="type == 'business'">
      <div class="just-box">
        <div class="upload-box" @click="uploadOcrApp('business')">
          <div class="perch-box" v-if="!business">
            <!-- <img :src="require('@/assets/business.png')" style="width: 100%; height: 100%" alt=""/> -->
            <div class="positon-box">
              <div class="camera-box">
                <!-- <img :src="require('@/assets/camera-fill.svg')" style="width: 70%" alt=""/> -->
              </div>
            </div>
          </div>
          <div class="return-box" v-if="business">
            <img :src="business" style="width: 100%; height: 100%" alt=""/>
          </div>
          <form ref="businessForm">
            <input
              ref="business"
              type="file"
              class="file-input"
              accept="image/*"
              @change="uploadBusinessImg"
              :disabled="isDisabled"
            />
          </form>
          <div class="loading-mask" v-if="uploadLoading.business">
            <spinner type="lines"></spinner>
          </div>
        </div>
        <div class="upload-hint">上传营业执照</div>
        <!-- <div>{{justInfo}}</div> -->
      </div>
    </div>

    <van-dialog v-model="showDialog" title="温馨提示" :show-cancel-button="false" :show-confirm-button="false">
      <p style="padding: 8px 24px 26px;color: #646566;" v-if="showDialogText">所选产品针对具有个体营业执照的个体工商户。无任何营业执照，可选择农户或者自雇人士客群进件！</p>
      <p style="padding: 8px 24px 26px;color: #646566;" v-else>所选产品针对具有工商企业营业执照的法人代表企业主。无任何营业执照，可选择农户或者自雇人士客群进件！</p>
      <div class="van-hairline--top van-dialog__footer">
        <div class="van-button van-button--default van-button--large van-dialog__cancel" @click="cancelFn">
          <div class="van-button__content">退出申请</div>
        </div>
        <div class="van-button van-button--default van-button--large van-dialog__confirm van-hairline--left" @click="confirmFn">
          <div class="van-button__content">农户申请</div>
        </div>
        <div class="van-button van-button--default van-button--large van-dialog__confirm van-hairline--left" @click="confirmFn">
          <div class="van-button__content">自雇申请</div>
        </div>
      </div>
    </van-dialog>
  </div>
</template>

<script>
import {Spinner} from "vux";
import common from "./plugins/common.js";

export default {
  name: "OCRUpload",
  components: {
    Spinner
  },
  /**
   * @param {String} type
   * idCard 身份证
   * business 营业执照
   * 不传默认为身份证
   * OCR验证主体类型
   */
  props: {
    capture: {
      type: String,
      default: ""
    },
    type: {
      type: String,
      default: "idCard"
    },
    frontFileType: {
      type: String,
      default: ""
    },
    backFileType: {
      type: String,
      default: ""
    },
    // 文件流水号
    fileNumber: {
      type: String,
      default: ""
    },
    instId: {
      type: String,
      default: ""
    },
    uuId: {
      type: String,
      default: ""
    },
    stateFlag: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      just: "",
      back: "",
      business: "",
      uploadLoading: {
        just: false,
        back: false,
        business: false
      },
      justInfo: {},
      backInfo: {},
      businessInfo: {},
      schema: "pc",
      isDisabled: false,
      showDialog: false,
      showDialogText: false,//true 个体工商户流程  false  企业主流程
    };
  },
  created() {
    console.log("当前uuid：：：", this.uuId)
  },
  mounted() {
    if (this.stateFlag) {
      if (this.type == 'idCard') {
        if (this.instId) {
          if (this.frontFileType) {
            this.getImageInfo(this.frontFileType, 'just')
          }
          if (this.backFileType) {
            this.getImageInfo(this.backFileType, 'back')
          }
        }
      } else if (this.type == 'business') {
        if (this.instId) {
          if (this.frontFileType) {
            this.getImageInfo(this.frontFileType, 'business')
          }
        }
      }
    }

    //获取UA信息
    let ua = this.$bridge.getDeviceType();
    // if (!ua || ua == "pc") {
    //   this.isDisabled = true;
    // }
    // this.schema = ua ? ua : 'pc';
  },
  methods: {
    // 获取图片反显信息
    getImageInfo(fileType, type) {
      let params = {
        fileNumber: this.instId,
        fileId: this.uuId,
        fileType: fileType,
      };
      this.baseService
        .getParams(`${this.__ctx}/attachment/listAll`, params)
        .then((res) => {
          if (res.isOk) {
            if (res.data.length > 0) {
              let url = res.data[0].fileAddress
              // if(this.$bridge.getDeviceType() == 'wechat') {
              // let arr = res.data[0].imageUrl.split('/')
              // arr[2] = this.__ctx
              // arr.splice(0, 2)
              // url = arr.join('/')
              // }
              url = this.__ctx + url
              console.info(url)
              switch (type) {
                case 'just':
                  this.just = url
                  break;
                case 'back':
                  this.back = url
                  break;
                case 'business':
                  this.business = url
                  break;
              }
            }
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    /**证件正面
     * @param {Object} e
     */
    async uploadJustImg(e) {
      if (e.target.files[0] === undefined) {
        return;
      }
      this.$vux.loading.show({
        text: "识别中，请稍后"
      });
      this.uploadLoading.just = true;
      let file = e.target.files[0];
      console.log("初始大小", file.size)
      let data = await common.compressionImage(file);
      if (
        data.type.indexOf("jpeg") == -1 &&
        data.type.indexOf("png") == -1
        // data.type.indexOf("bmp") == -1 &&
        // data.type.indexOf("gif") == -1
      ) {
        this.$vux.loading.hide();
        this.$vux.toast.show({
          text: "请上传jpeg/png的图片",
          type: "warn"
        });
        this.uploadLoading.just = false;
        return;
      }
      //获取图片分辨率
      // const fileBase64 = await this.getBase64(data);
      // const res = await this.getImgPx(fileBase64);
      // // this.px = res.width + 'px *' + res.height + 'px';
      // console.log("hhhhhhhhhhhhhhhhhh", res.width + 'px *' + res.height + 'px')
      // if (res.width > 4000 || res.height > 2000) {
      //   this.$vux.loading.hide();
      //   this.$vux.toast.show({
      //     text: "图片分辨率过大，请重新上传",
      //     type: "warn"
      //   });
      //   this.uploadLoading.just = false;
      //   return;
      // }

      let mb = 1024 * 1024;
      let maxSize = 5 * mb;
      // 如果压缩之后还大于5M再压缩一次
      console.log('data.size', data.size)
      console.log('maxSizemaxSize', maxSize)

      if (data.size >= maxSize) {
        data = await common.compressionImage(data)
      }
      console.log('压缩2后data.size', data.size)
      console.log('压缩2后maxSizemaxSize', maxSize)
      console.log("当前图片------", data)
      if (data.size >= maxSize) {
        this.$vux.loading.hide();
        this.$vux.toast.show({
          text: "请上传小于5MB的图片",
          type: "warn"
        });
        this.uploadLoading.just = false;
        return;
      }
      let reader = new FileReader();
      reader.readAsDataURL(data);
      let that = this;
      reader.onload = () => {
        that.just = reader.result;
        let requestData = {
          // num: "IML01",
          // ocrType: "00000001",
          // image64: reader.result,
          // instId: that.instId,
          // fileType: that.frontFileType,
          // uuId: that.uuId
          imageBase64: reader.result
        };
        //上传需要的参数
        let base64UploadDTOs = [
          {
            ocrType: 'idCardJust',
            fileNumber: that.instId || that.uuId,
            fileType: that.frontFileType,
            base64: reader.result,
            fileName: file.name,//文件名
            fileSuffix: '.' + file.name.substring(file.name.lastIndexOf('.') + 1),//文件后缀
          },
        ];
        let upload = common.UploadOCR(requestData);

        upload.then(res => {
          this.$vux.loading.hide();
          that.uploadLoading.just = false;
          //判断是否是身份证头像面
          if (res.data.length <= 0 || res.data[0].side != "front") {
            this.$vux.toast.show({text: '请上传/拍摄身份证头像面', type: 'warn',})
            that.just = "";
            that.$refs.justForm.reset();
            this.resetData('just')
            return
          }
          // ***************反向案例start****************
          // if(res.data[0].name == '张盼盼'){
          //   that.$dialog.confirm({
          //     title: '温馨提示',
          //     message: '您录入的法定代表人股权比例过低，需增加实控人或股东，点击继续申请进行产品更换。',
          //     confirmButtonText: '继续申请',
          //     cancelButtonText: '退出申请',
          //   }).then(() => {
          //     // on confirm
          //   }).catch(() => {
          //     // on cancel
          //     that.$router.back();
          //   });
          //   that.just = "";
          //   that.$refs.justForm.reset();
          //   that.resetData('just')
          //   return
          // }
          // ***************反向案例end****************
          //  识别成功后上传
          that.UploadImage(base64UploadDTOs)

          this.justInfo = res.data[0];
          that.$refs.justForm.reset();
          // 回调方法名需是全小写，否则表单接收不到方法
          this.$emit("getocrinfo", {
            type: this.type,
            face: "just",
            data: res.data[0]
          });

        }).catch(error => {
          that.just = "";
          that.$refs.justForm.reset();
          this.$vux.loading.hide();
          that.uploadLoading.just = false;
          this.resetData('just')
          this.$vux.toast.show({text: error, type: 'warn'})
        });
      };
    },
    //file转base64
    getBase64(file) {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      return new Promise((resolve) => {
        reader.onload = () => {
          resolve(reader.result);
        };
      });
    },
    //获取图片分辨率
    getImgPx(img) {
      const image = new Image();
      image.src = img;
      return new Promise((resolve) => {
        image.onload = () => {
          const width = image.width;
          const height = image.height;
          resolve({width, height});
        };
      });
    },
    /**
     * 证件背面
     * @param e
     * @returns {Promise<void>}
     */
    async uploadBackImg(e) {
      if (e.target.files[0] === undefined) {
        return;
      }
      this.$vux.loading.show({
        text: "识别中，请稍后"
      });
      this.uploadLoading.back = true;
      let file = e.target.files[0];
      let data = await common.compressionImage(file);
      if (
        data.type.indexOf("jpeg") == -1 &&
        data.type.indexOf("png") == -1
        // data.type.indexOf("bmp") == -1 &&
        // data.type.indexOf("gif") == -1
      ) {
        this.$vux.loading.hide();
        this.$vux.toast.show({
          text: "请上传jpeg/png的图片",
          type: "warn"
        });
        this.uploadLoading.back = false;
        return;
      }
      let mb = 1024 * 1024;
      let maxSize = 5 * mb;
      // 如果压缩之后还大于5M再压缩一次
      if (data.size >= maxSize) {
        data = await common.compressionImage(data)
      }
      if (data.size >= maxSize) {
        this.$vux.loading.hide();
        this.$vux.toast.show({
          text: "请上传小于5MB的图片",
          type: "warn"
        });
        this.uploadLoading.back = false;
        return;
      }
      let reader = new FileReader();
      reader.readAsDataURL(data);
      let that = this;
      reader.onload = () => {
        that.back = reader.result;
        // let backData = {
        //   "ocrType": "00000001",
        //   "remoteFile": "/iml/iml001/data/esc/ftsDir/iml/iml001/iml/iml001/2.jpg",
        //   "image_url": "http://172.25.161.241:8080/httpfiletrans/HttpFileTrans?method=download&BufferSize=65536&FlushSize=65536&IsCreateDir=TRUE&FilePath=/user/testCT/image_dir/IML/2022/9/21/IML0831/240828f87fd840258b54b0e21efc0fdf.jpg&uploadFlag=0&bucketName=nia-bucket-com-1",
        //   "num": "IML01"
        // }
        let requestData = {
          // num: "IML01",
          // ocrType: "00000001",
          // image64: reader.result,
          // instId: that.instId,
          // fileType: that.backFileType,
          // uuId: that.uuId,
          imageBase64: reader.result,
        };
        //上传需要的参数
        let base64UploadDTOs = [
          {
            ocrType: 'idCardBack',
            fileNumber: that.instId || that.uuId,
            fileType: that.backFileType,
            base64: reader.result,
            fileName: file.name,//文件名
            fileSuffix: '.' + file.name.substring(file.name.lastIndexOf('.') + 1),//文件后缀
          },
        ];
        let upload = common.UploadOCR(requestData);
        upload.then(res => {
          this.$vux.loading.hide();
          that.uploadLoading.back = false;
          //判断是否是身份证头像面
          if (res.data.length <= 0 || res.data[0].side != "back") {
            this.$vux.toast.show({text: '请上传/拍摄身份证国徽面', type: 'warn'})
            that.back = "";
            that.$refs.backForm.reset();
            this.resetData('back')
            return
          }
          this.UploadImage(base64UploadDTOs)

          this.backInfo = res.data[0];
          that.$refs.backForm.reset();
          this.$emit("getocrinfo", {
            type: this.type,
            face: "back",
            data: res.data[0]
          });

        }).catch(error => {
          this.$vux.loading.hide();
          that.back = "";
          that.$refs.backForm.reset();
          that.uploadLoading.back = false;
          this.resetData('back')
          this.$vux.toast.show({
            text: error,
            type: 'warn',
          })
        });
      };
    },
    /**
     * 营业执照
     * @param e
     * @returns {Promise<void>}
     */
    async uploadBusinessImg(e) {
      if (e.target.files[0] === undefined) {
        return;
      }
      this.$vux.loading.show({
        text: "识别中，请稍后"
      });
      this.uploadLoading.business = true;
      let file = e.target.files[0];
      let data = await common.ImageCompress(file);
      if (
        data.type.indexOf("jpeg") == -1 &&
        data.type.indexOf("png") == -1
        // data.type.indexOf("bmp") == -1 &&
        // data.type.indexOf("gif") == -1
      ) {
        this.$vux.loading.hide();
        this.$vux.toast.show({
          text: "请上传jpeg/png的图片",
          type: "warn"
        });
        this.uploadLoading.business = false;
        return;
      }
      let mb = 1024 * 1024;
      let maxSize = 5 * mb;
      // 如果压缩之后还大于5M再压缩一次
      if (data.size >= maxSize) {
        data = await common.ImageCompress(data)
      }
      if (data.size >= maxSize) {
        this.$vux.loading.hide();
        this.$vux.toast.show({
          text: "请上传小于5MB的图片",
          type: "warn"
        });
        this.uploadLoading.business = false;
        return;
      }
      let reader = new FileReader();
      reader.readAsDataURL(data);
      let that = this;
      reader.onload = () => {
        that.business = reader.result;
        // let backData = {
        //   "ocrType": "00000008",
        //   "remoteFile": "/iml/iml001/data/esc/ftsDir/iml/iml001/iml/iml001/3.jpg",
        //   "image_url": "http://172.25.161.241:8080/httpfiletrans/HttpFileTrans?method=download&BufferSize=65536&FlushSize=65536&IsCreateDir=TRUE&FilePath=/user/testCT/image_dir/IML/2022/9/21/IML0831/f16a2a2cd6654455a8482c2059908e05.jpg&uploadFlag=0&bucketName=nia-bucket-com-1",
        //   "num": "IML01"
        // }
        let requestData = {
          // num: "IML01",
          // ocrType: "00000008",
          // image64: reader.result,
          // instId: that.instId,
          // fileType: that.frontFileType,
          // uuId: that.uuId,
          imageBase64: reader.result,
        };
        //上传需要的参数
        let base64UploadDTOs = [
          {
            ocrType: 'business',
            fileNumber: that.instId || that.uuId,
            fileType: that.frontFileType,
            base64: reader.result,
            fileName: file.name,//文件名
            fileSuffix: '.' + file.name.substring(file.name.lastIndexOf('.') + 1),//文件后缀
          },
        ];
        let upload = common.UploadYyzzOCR(requestData);
        upload.then(res => {
          this.$vux.loading.hide();
          that.uploadLoading.business = false;
          //判断是否是身份证头像面
          if (!res.data) {
            this.$vux.toast.show({text: '请上传/拍摄正确营业执照图片', type: 'warn'})
            that.business = "";
            that.resetData('business')
            return
          }
          // ***************反向案例start****************
          if (res.data.enterprise_name == '北京瑞天科技有限公司') {
            that.$vux.toast.show({text: '您的工商营业执照注册地非本省，抱歉，您的申请不符合准入要求。', type: 'warn', time: 6000})
            that.business = "";
            that.resetData('business')
            return
          }
          if (res.data.enterprise_name == '北京瑞天欣实') {
            that.$dialog.confirm({
              title: '温馨提示',
              message: '所选产品针对具有个体营业执照的个体工商户。该经营执照为企业营业执照，可选择企业主客群进件！',
              confirmButtonText: '企业主申请',
              cancelButtonText: '退出申请',
            }).then(() => {
              // on confirm
            }).catch(() => {
              // on cancel
              that.$router.back();
            });
            that.business = "";
            that.resetData('business')
            return
          }
          if (res.data.enterprise_name == '瑞天欣实科技') {  //个体工商户
            that.showDialog = true;
            that.showDialogText = true;
            that.business = "";
            that.resetData('business')
            return
          }
          if (res.data.enterprise_name == '瑞天科技有限公司') {   //企业主
            that.showDialog = true;
            that.showDialogText = false;
            that.business = "";
            that.resetData('business')
            return
          }
          if (res.data.enterprise_name == '个体工商户非企业主') {
            that.$dialog.confirm({
              title: '温馨提示',
              message: '所选产品针对具有经营执照为企业营业执照的企业主。该经营执照为个体营业执照的个体工商户，可选择个体工商户客群进件！',
              confirmButtonText: '个体工商户申请',
              cancelButtonText: '退出申请',
            }).then(() => {
              // on confirm
            }).catch(() => {
              // on cancel
              that.$router.back();
            });
            that.business = "";
            that.resetData('business')
            return
          }
          if (res.data.enterprise_name == '无独立法人资格') {  //无独立法人资格
            that.$vux.toast.show({text: '您的工商营业执照不具备独立法人资格，抱歉，您的申请不符合准入要求。', type: 'warn', time: 6000})
            that.business = "";
            that.resetData('business')
            return
          }
          // ***************反向案例end****************
          that.UploadImage(base64UploadDTOs)
          that.$refs.businessForm.reset();
          this.businessInfo = res.data;
          this.$emit("getocrinfo", {
            type: this.type,
            data: res.data
          });
        }).catch(error => {
          that.business = "";
          that.$refs.businessForm.reset();
          this.$vux.loading.hide();
          that.uploadLoading.business = false;
          this.resetData('business')
          this.$vux.toast.show({
            text: error,
            type: 'warn',
          })
        });
      };
    },

    // 关闭提示
    confirmFn() {
      this.showDialog = false;
    },
    cancelFn() {
      this.showDialog = false;
      this.$router.back();
    },

    /**
     * 上传图片方法
     * @param base64Strs
     * @returns {Promise<unknown>}
     * @constructor
     */
    async UploadImage(base64Strs) {
      console.log("上柴男--------", base64Strs)
      let that = this
      let base64Strings = base64Strs;
      this.baseService.post(this.__ctx + "/attachment/upload/base64", base64Strings).then((res) => {
        if (res.isOk) {
          this.$nextTick(() => {
            if (res.data[0].fileName.substring(res.data[0].fileName.lastIndexOf('.') + 1) == 'jpg' || res.data[0].fileName.substring(res.data[0].fileName.lastIndexOf('.') + 1) == 'png') {
              let a = this.__ctx
              if (base64Strs[0].ocrType == 'idCardJust') {
                that.just = a + res.data[0].url
              } else if (base64Strs[0].ocrType == 'idCardBack') {
                that.back = a + res.data[0].url
              } else if (base64Strs[0].ocrType == 'business') {
                that.business = a + res.data[0].url
              }
            }
          });
          that.$vux.toast.show({text: res.msg, type: 'success'})
        } else {
          that.$vux.toast.show({text: res.msg, type: 'error'})
        }
      }).catch((error) => {
        // reject(error);
      });
    },

    uploadOcrApp(type) {
      if (
        (this.schema != "android" && this.schema != "ios") ||
        type == "business"
      ) {
        return;
      }
      // if (this.schema == "android") {
      // 0 反面，1 正面
      let cardType = type == "justCard" ? 1 : 0;
      //  window.tool.startIdCardOcr(cardType);
      let that = this;
      // console.log('type =>' + type)
      // this.$bridge.idCardOcr({ ocrFlag: cardType }, response => {
      //   if (response) {
      //     let ocrInfo = JSON.parse(response);
      //     that.setOcrInfo(cardType,ocrInfo);
      //   }else {
      //     that.resetData(cardType == 1 ? 'just' : 'back')
      //   }
      // });
      // } else {
      //   console.log("暂不支持IOS");
      // }
    },

    setOcrInfo(type, ocrInfo) {
      try {
        let obj = ocrInfo;
        let keys = Object.keys(obj);
        let ocrData = [];
        let that = this;
        keys.forEach(v => {
          let tobj = {};
          switch (v) {
            case "idFrontStr":
              if (obj[v]) {
                let uuid = "";
                if (that.uuId) {
                  uuid = that.uuId;
                } else {
                  uuid = that.instId;
                }
                let justBase64Str = {
                  fileType: that.frontFileType,
                  base64: "data:image/jpeg;base64," + obj[v],
                  fileNumber: uuid
                };
                common.UploadImage([justBase64Str]);
                that.just = "data:image/jpeg;base64," + obj[v];
              }
              break;
            case "idBackStr":
              if (obj[v]) {
                let uuid = "";
                if (that.uuId) {
                  uuid = that.uuId;
                } else {
                  uuid = that.instId;
                }
                let backBase64Str = {
                  fileType: that.backFileType,
                  base64: "data:image/jpeg;base64," + obj[v],
                  fileNumber: uuid
                };
                common.UploadImage([backBase64Str]);
                that.back = "data:image/jpeg;base64," + obj[v];
              }
              break;
            case "name":
              if (obj[v]) {
                tobj.itemid = "name";
                tobj.itemstring = obj[v];
                ocrData.push(tobj);
              }
              break;
            case "id":
              if (obj[v]) {
                tobj.itemid = "id";
                tobj.itemstring = obj[v];
                ocrData.push(tobj);
              }
              break;
            case "address":
              if (obj[v]) {
                tobj.itemid = "address";
                tobj.itemstring = obj[v];
                ocrData.push(tobj);
              }
              break;
            case "birth":
              if (obj[v]) {
                tobj.itemid = "birth";
                // tobj.itemstring = obj[v];
                let date1 = obj[v].replace(/[年月]/g, "/");
                tobj.itemstring = date1.replace(/[日]/g, "");
                ocrData.push(tobj);
              }
              break;
            case "sex":
              if (obj[v]) {
                tobj.itemid = "sex";
                tobj.itemstring = obj[v];
                ocrData.push(tobj);
              }
              break;
            case "race":
              if (obj[v]) {
                tobj.itemid = "nation";
                tobj.itemstring = obj[v];
                ocrData.push(tobj);
              }
              break;
            case "authority":
              if (obj[v]) {
                tobj.itemid = "authority";
                tobj.itemstring = obj[v];
                ocrData.push(tobj);
              }
              break;
            case "startValidate":
              if (obj[v]) {
                tobj.itemid = "valid_date";
                let start = `${obj[v].substr(0, 4)}.${obj[v].substr(
                  4,
                  2
                )}.${obj[v].substr(6, 2)}`;
                let end = `${obj.endValidate.substr(
                  0,
                  4
                )}.${obj.endValidate.substr(4, 2)}.${obj.endValidate.substr(
                  6,
                  2
                )}`;
                tobj.itemstring = start + "-" + end;
                ocrData.push(tobj);
              }
              break;
          }
        });
        this.$emit("getocrinfo", {
          type: this.type,
          data: ocrData
        });
      } catch (error) {
        console.error(error);
        this.resetData(type == 1 ? 'just' : 'back')
      }
    },

    resetData(type) {
      if (type == 'just') {
        let data = {
          name: '',
          id: '',
          address: '',
          birth: '',
          nation: '',
          sex: ''
        }
        this.$emit("getocrinfo", {
          type: this.type,
          data: data
        });
      } else if (type == 'back') {
        let data = {
          authority: '',
          valid_date: ''
        }
        this.$emit("getocrinfo", {
          type: this.type,
          data: data
        });
      } else {
        let data = {
          bizlicensePerson: '',
          bizlicenseName: '',
          bizlicenseType: '',
          business_range: '',
          bizlicenseCapital: '',
          bizlicenseAddress: '',
          bizlicenseNumber: '',
          bizlicenseDate: ''
        }
        this.$emit("getocrinfo", {
          type: this.type,
          data: data
        });
      }
    }
  }
};
</script>

<style>
.ocr-box {
  display: flex;
  align-items: center;
  justify-content: space-around;
  margin: 1.6rem 0;
}

.just-box,
.back-box {
  /*width: 50%;*/
  position: relative;
}

.camera-box {
  width: 20%;
  border-radius: 50%;
  /* background-color: rgba(90, 143, 255, 0.9); */
  background: linear-gradient(360deg, #9da1ac 0%, #9da1ac 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  /* box-sizing: border-box; */
  padding: 3% 0;
}

.positon-box {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-mask {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 3;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 255, 255, 0.6);
}

.perch-box {
  position: relative;
  height: 9rem;
  width: 15rem;
}

.file-input {
  position: absolute;
  z-index: 2;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  opacity: 0;
}

.upload-box {
  /* background-color: #F5F5F5; */
  /*margin: 8px 10px;*/
  border-radius: 6px;
  position: relative;
}

.return-box {
  height: 9rem;
  width: 15rem;
}

.upload-hint {
  /*text-align: center;*/
  /*font-size: 14px;*/
  color: #1D21298A;
  margin-top: 1.2rem;
  font-family: HarmonyOS Sans SC;
  font-size: 14px;
  font-weight: 400;
  line-height: 16px;
  text-align: center;
}

.van-dialog__confirm, .van-dialog__confirm:active {
  color: var(--primary-color) !important;
}
</style>
